import BaseButton from '@/components/base/BaseButton';
import BaseForm, {
  BaseFormSelect,
  ProFormCheckbox,
  ProFormDependency,
  ProFormInstance
} from '@/components/base/BaseForm';
import BasePageFrame from '@/components/base/BasePageFrame';
import Battery from '@/pages/monitor/components/Battery';
import { fixHeight, fixWidth } from '@/pages/monitor/util';
import { getList as getKeyPartsModelList } from '@/pages/radar/keyParts/KeyPartsModelInfo/api';
import { getList as getRadarList } from '@/pages/radar/RadarInfo/api';
import { getList as getRadarTypeList } from '@/pages/radar/RadarTypeInfo/api';
import { useRequest } from '@/utils/request';
import { Alert, Card, Col, ConfigProvider, Empty, message, Row, Spin } from 'antd';
import { useRef } from 'react';
import styled from 'styled-components';
import { getLifeModel, getLifePieceModel } from '../api';

const Wrap = styled.div`
  .ant-checkbox-group-item {
    margin: 12px 0;
  }
`;
const ResultList = styled.div`
  display: flex;
  flex-direction: column;
`;
const ResultListItem = styled.div`
  margin: ${fixHeight(20)} auto;
  display: flex;
  width: 420px;
`;
const LifeInfo = styled.div`
  flex: 1;
  padding-left: ${fixWidth(16)};
`;
const LifeInfoItem = styled.div`
  display: flex;
  width: 100%;
  margin: 5px 0;
  span {
    width: 50%;
    font-size: ${fixHeight(14)};
  }
`;
const RULSimulation = () => {
  const form = useRef<ProFormInstance>();
  const lifeModel = useRequest(getLifeModel, {
    manual: true
  });
  const lifePieceModel = useRequest(getLifePieceModel, {
    manual: true
  });
  return (
    <BasePageFrame>
      <Card style={{ height: '100%' }} bodyStyle={{ height: '100%' }}>
        <Row style={{ height: '100%' }} gutter={16}>
          <Col span={10}>
            <BaseForm
              formRef={form}
              labelCol={{ style: { width: 120 } }}
              layout='horizontal'
              submitter={{
                render: (props) => {
                  return (
                    <BaseButton
                      type='primary'
                      block
                      loading={lifePieceModel.loading}
                      onClick={() => {
                        props.submit();
                      }}
                    >
                      获取算法结果
                    </BaseButton>
                  );
                }
              }}
              onFinish={async (values) => {
                if (values.ids && values.ids.length > 0) {
                  lifePieceModel.run(values);
                } else {
                  lifePieceModel.mutate([]);
                  message.warning('请先选择算法模型');
                }
              }}
            >
              <h3>请选择仿真寿命件数据</h3>
              <BaseFormSelect
                label='雷达型号'
                name='radarTypeId'
                request={getRadarTypeList}
                placeholder='请选择雷达型号'
                fieldProps={{
                  fieldNames: { label: 'name', value: 'id' },
                  onChange: () => {
                    form.current?.setFieldsValue({
                      keyPartsModelId: undefined,
                      radarId: undefined
                    });
                  }
                }}
                rules={[{ required: true, message: '请选择雷达型号' }]}
              />
              <ProFormDependency name={['radarTypeId']}>
                {({ radarTypeId }) => {
                  return (
                    <ConfigProvider
                      renderEmpty={() => (
                        <Empty
                          image={Empty.PRESENTED_IMAGE_SIMPLE}
                          description='暂无可进行仿真的雷达，请检查雷达类型下有绑定雷达，且雷达已有数据表'
                        />
                      )}
                    >
                      <BaseFormSelect
                        label='雷达'
                        name='radarId'
                        placeholder='请选择雷达'
                        hiddenItem={!radarTypeId}
                        hiddenRender={() => <Alert type='warning' message='请先选择雷达型号' />}
                        fieldProps={{
                          params: { typeId: radarTypeId, isRUL: 1 },
                          fieldNames: { label: 'name', value: 'id' },
                          onChange: () => {
                            lifePieceModel.mutate([]);
                            form.current?.setFieldsValue({ keyPartsModelId: undefined });
                          }
                        }}
                        request={getRadarList}
                        rules={[
                          {
                            required: true,
                            message: radarTypeId ? '请选择雷达' : '请先选择雷达型号'
                          }
                        ]}
                      />
                    </ConfigProvider>
                  );
                }}
              </ProFormDependency>
              <ProFormDependency name={['radarId']}>
                {({ radarId }) => {
                  return (
                    <ConfigProvider
                      renderEmpty={() => (
                        <Empty
                          image={Empty.PRESENTED_IMAGE_SIMPLE}
                          description='暂无可用的雷达寿命件'
                        />
                      )}
                    >
                      <BaseFormSelect
                        label='寿命件'
                        name='keyPartsModelId'
                        placeholder='请选择雷达寿命件'
                        hiddenItem={!radarId}
                        hiddenRender={() => <Alert type='warning' message='请先选择雷达' />}
                        request={getKeyPartsModelList}
                        fieldProps={{
                          params: { radarId, isLife: 1 },
                          fieldNames: {
                            label: (data: any) => `${data.typeName ?? ''}${data.name ?? ''}`,
                            value: 'id'
                          },
                          onChange: (v) => {
                            form.current?.setFieldsValue({ ids: undefined });
                            lifeModel.run({ keyPartsModelId: v });
                            lifePieceModel.mutate([]);
                          }
                        }}
                        rules={[
                          { required: true, message: radarId ? '请选择雷达寿命件' : '请先选择雷达' }
                        ]}
                      />
                    </ConfigProvider>
                  );
                }}
              </ProFormDependency>
              <Spin spinning={lifeModel.loading}>
                <Wrap>
                  {lifeModel.data && lifeModel.data.length > 0 ? (
                    <ProFormCheckbox.Group
                      name='ids'
                      label='仿真算法模型'
                      fieldProps={{
                        style: {
                          display: 'flex',
                          justifyContent: 'space-around',
                          flexDirection: 'column'
                        }
                      }}
                      options={lifeModel.data.map((i) => ({ label: i.cname, value: i.id }))}
                    />
                  ) : (
                    <BaseForm.Item label='仿真算法模型' name='ids'>
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description='暂无可用的仿真算法模型'
                      />
                    </BaseForm.Item>
                  )}
                </Wrap>
              </Spin>
            </BaseForm>
          </Col>
          <Col span={14}>
            {lifePieceModel.data && lifePieceModel.data.length > 0 ? (
              <ResultList>
                {(lifePieceModel.data ?? []).map((i) => (
                  <ResultListItem>
                    <Battery percent={i.residualLife / (i.activeLife + i.residualLife)}>
                      <div className='battery-info'>
                        {((i.residualLife * 100) / (i.activeLife + i.residualLife)).toFixed(2)}%
                      </div>
                    </Battery>
                    <LifeInfo>
                      <LifeInfoItem>
                        <b>{i.taAlgorithmModelName}</b>
                      </LifeInfoItem>
                      <LifeInfoItem>
                        {i.typeName}
                        {i.name}
                      </LifeInfoItem>
                      <LifeInfoItem>
                        <span>总寿命</span>
                        <span>{i.totalLife} h</span>
                      </LifeInfoItem>
                      <LifeInfoItem>
                        <span>已使用寿命</span>
                        <span>{i.activeLife} h</span>
                      </LifeInfoItem>
                      <LifeInfoItem>
                        <span>预计剩余寿命</span>
                        <span>{i.residualLife} h</span>
                      </LifeInfoItem>
                      <LifeInfoItem>
                        <span>预计失效时间</span>
                        <span>{i.failureTime}</span>
                      </LifeInfoItem>
                      <LifeInfoItem>
                        <span>置信度</span>
                        <span>{i.confidence * 100}%</span>
                      </LifeInfoItem>
                    </LifeInfo>
                  </ResultListItem>
                ))}
              </ResultList>
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='暂无仿真结果' />
            )}
          </Col>
        </Row>
      </Card>
    </BasePageFrame>
  );
};

export default RULSimulation;
